<template>
  <div class="customer-edit-page">
    <van-nav-bar
      title="编辑客户"
      left-arrow
      @click-left="router.back()"
    />

    <div v-if="loading" class="loading-container">
      <van-loading type="spinner" size="24px" vertical />
    </div>

    <div v-else class="page-content">
      <van-form @submit="onSubmit">
        <!-- 基本信息表单 -->
        <div class="form-section">
          <van-cell-group inset>
            <van-field
              v-model="customerForm.buyerName"
              name="buyerName"
              label="姓名"
              placeholder="请输入客户姓名"
              :rules="[{ required: true, message: '请填写客户姓名' }]"
            />
            <van-field
              v-model="customerForm.contact"
              type="tel"
              name="contact"
              label="联系方式"
              placeholder="请输入联系方式（选填）"
            />
          </van-cell-group>
        </div>
        
        <!-- 头像上传 -->
        <div class="avatar-section">
          <div class="section-title">上传头像</div>
          <van-uploader
            v-model="fileList"
            :max-count="1"
            :after-read="afterRead"
            :before-read="beforeRead"
            :max-size="5 * 1024 * 1024"
            @oversize="onOversize"
            accept="image/*"
            :preview-options="{
              closeable: true,
              showIndex: false
            }"
            :preview-image="true"
            :preview-full-image="true"
            :deletable="true"
            @delete="onDelete"
          >
            <template #default>
              <div class="upload-area" v-if="fileList.length === 0">
                <van-icon name="plus" size="24" />
                <div class="upload-text">上传头像</div>
              </div>
            </template>
          </van-uploader>
          <div class="upload-tip">支持jpg、png格式，大小不超过5MB</div>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <van-button round block type="primary" native-type="submit" :loading="submitting">
            保存修改
          </van-button>
          <van-button round block plain @click="router.back()" style="margin-top: 12px">
            取消
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { showToast } from 'vant'
import type { UploaderFileListItem } from 'vant'
import { getCustomerDetail, updateCustomer } from '../api/customer'

const router = useRouter()
const route = useRoute()
const loading = ref(false)
const submitting = ref(false)
const fileList = ref<UploaderFileListItem[]>([])

// 客户表单
const customerForm = ref({
  id: '',
  buyerName: '',
  contact: '',
  address: '',
  notes: '',
  avatarUrl: '',
  totalAmount: 0,
  orderCount: 0,
  lastVisit: ''
})

// 文件上传前的校验
const beforeRead = (file: File | File[]) => {
  const files = Array.isArray(file) ? file : [file]
  const isImage = files.every(f => f.type === 'image/jpeg' || f.type === 'image/png')
  if (!isImage) {
    showToast('请上传jpg或png格式的图片')
    return false
  }
  return true
}

// 文件大小超出限制
const onOversize = () => {
  showToast('文件大小不能超过5MB')
}

// 文件上传后的处理
const afterRead = (items: UploaderFileListItem | UploaderFileListItem[]) => {
  const files = Array.isArray(items) ? items : [items]
  const file = files[0]?.file
  if (!file) return

  const reader = new FileReader()
  reader.onload = (e) => {
    const result = e.target?.result as string
    customerForm.value.avatarUrl = result
    fileList.value = [{
      url: result,
      file,
      isImage: true
    }]
  }
  reader.readAsDataURL(file)
}

// 删除文件后的处理
const onDelete = () => {
  fileList.value = []
  customerForm.value.avatarUrl = ''
}

// 初始化时从API获取客户信息
const fetchCustomerData = async (id: string) => {
  loading.value = true
  try {
    const customer = await getCustomerDetail(id)
    customerForm.value = {
      id: customer.id,
      buyerName: customer.buyerName || '',
      contact: customer.contact || '',
      address: customer.address || '',
      notes: customer.notes || '',
      avatarUrl: customer.image || '', // 保存当前头像到avatarUrl字段
      totalAmount: customer.totalAmount || 0,
      orderCount: customer.orderCount || 0,
      lastVisit: customer.lastVisit || ''
    }
    
    // 如果有头像，添加到文件列表
    if (customer.image) {
      fileList.value = [{
        url: customer.image,
        isImage: true
      }]
    }
  } catch (error) {
    console.error('获取客户详情失败:', error)
    showToast('未找到客户信息，请返回重试')
    router.back()
  } finally {
    loading.value = false
  }
}

// 编辑客户提交
const onSubmit = async () => {
  if (!customerForm.value.buyerName) {
    showToast('请输入客户姓名')
    return
  }
  
  submitting.value = true
  try {
    // 更新客户数据
    const updatedCustomer = {
      id: customerForm.value.id,
      buyerName: customerForm.value.buyerName,
      contact: customerForm.value.contact,
      image: customerForm.value.avatarUrl,
      address: customerForm.value.address,
      notes: customerForm.value.notes
    }
    
    await updateCustomer(customerForm.value.id, updatedCustomer)
    showToast('客户信息更新成功')
    router.back()
  } catch (error) {
    console.error('更新客户失败:', error)
    showToast('更新客户信息失败')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  const id = route.params.id as string
  if (!id) {
    showToast('客户ID无效')
    router.back()
    return
  }
  
  fetchCustomerData(id)
})
</script>

<style lang="scss" scoped>
.customer-edit-page {
  min-height: 100vh;
  background: #f7f8fa;
  display: flex;
  flex-direction: column;

  .loading-container {
    flex: 1;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .page-content {
    flex: 1;
    padding: 12px;
  }

  .form-section {
    margin-bottom: 12px;
    background: #fff;
    border-radius: 8px;
    overflow: hidden;
  }

  .avatar-section {
    margin-top: 12px;
    padding: 16px;
    background: #fff;
    border-radius: 8px;

    .section-title {
      margin-bottom: 16px;
      font-size: 14px;
      color: #323233;
      font-weight: 500;
    }

    .upload-area {
      width: 100px;
      height: 100px;
      background: #f7f8fa;
      border-radius: 8px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      color: #969799;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background: #f2f3f5;
      }

      .upload-text {
        margin-top: 8px;
        font-size: 12px;
      }
    }

    .upload-tip {
      margin-top: 8px;
      font-size: 12px;
      color: #969799;
    }
  }

  .form-actions {
    margin: 24px 12px;
    
    .van-button {
      height: 44px;
      font-size: 16px;
    }
  }
}

:deep(.van-cell-group) {
  margin: 0 !important;
}

:deep(.van-cell) {
  padding: 12px 16px !important;
}

:deep(.van-field__label) {
  width: 60px;
  color: #323233;
}

:deep(.van-cell-group--inset) {
  margin: 0 !important;
}

:deep(.van-uploader__preview-image) {
  width: 100px;
  height: 100px;
  border-radius: 8px;
}

:deep(.van-uploader__preview) {
  margin: 0;
}
</style> 